const db = wx.cloud.database();
Page({
  data: {
    petId: "",
    showDeleteBtn: false,
    uploadImgs: [],
    showLikeBtn: false,
    picLiker: 0,
    picLikeCount: 0,
    page: 1,
    totalCount: 0, //数据总数
    pet_like_id: '', // 点赞记录id
    arrPicId: [], // 图片列表id
    // 如果会写样式的童鞋，可以换种写法，这个太麻烦了，
    // 可以将checkbox-group放在最外层，根据e.detail.value获取选择的id数组，循环获取id并push，这样简单一些。
    // 俺对写css不熟练 调起来太慢，可能这就是后端程序员的痛吧。
    chooseList: [], // 判断是否选中   
    loadProgress: 0
  },
  onLoad: function (options) {
    this.setData({
      petId: options.petId
    })
    this.loadPetDet();
    this.getPetPics();
    this.getTotalCount();
    // 判断是否点赞
    this.isLike();
  },
  /**
   * 获取总数
   */
  getTotalCount() {
    let that = this;
    db.collection('p_pet_pics').where({
      petId: this.data.petId,
      activeFlag: 1
    }).count({
      success: function (res) {
        console.log(res.total);
        that.setData({
          totalCount: res.total
        })
      }
    })
  },
  /**
   * 获取宠物信息
   */
  loadPetDet() {
    db.collection('p_pets').where({
      _id: this.data.petId
    }).get({
      success: res => {
        let info = res.data[0];
        let showLikeBtn = true;
        if (info._openid == wx.getStorageSync('openid')) {
          showLikeBtn = false
        }
        this.setData({
          pet: info,
          showLikeBtn: showLikeBtn,
          picLikeCount: info.picLikeCount
        });
        this.treatmentVelocity();
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  /**
   * 获取狗狗写真集列表
   */
  getPetPics() {
    db.collection('p_pet_pics').where({
      petId: this.data.petId,
      activeFlag: 1
    }).skip(0)
      .limit(8).get({
        success: res => {
          let pics = res.data;
          let arrPic = [];
          let arrId = [];
          let chooseList = [];
          for (let i = 0; i < pics.length; i++) {
            arrPic.push(pics[i].picPath);
            arrId.push(pics[i]._id);
            chooseList.push(false);
          }
          this.setData({
            uploadImgs: arrPic,
            arrPicId: arrId,
            chooseList: chooseList
          })
        },
        fail: err => {
          console.log('[数据库] [查询记录] 失败：');
        }
      })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let page = this.data.page;
    if (this.data.uploadImgs.length < this.data.totalCount) {
      db.collection('p_pet_pics').where({
        petId: this.data.petId,
        activeFlag: 1
      }).skip(page * 8)
        .limit(8).get({
          success: res => {
            let pics = res.data;
            let arrPic = this.data.uploadImgs;
            let arrId = this.data.arrPicId;
            let chooseList = this.data.chooseList;
            for (let i = 0; i < pics.length; i++) {
              arrPic.push(pics[i].picPath);
              arrId.push(pics[i]._id);
              chooseList.push(false);
            }
            this.setData({
              uploadImgs: arrPic,
              page: page + 1,
              arrPicId: arrId,
              chooseList: chooseList
            })

            wx.hideNavigationBarLoading(); //隐藏加载
          },
          fail: err => {
            console.log('[数据库] [查询记录] 失败：');
          }
        })
    } else {
      wx.showToast({
        title: '没有更多数据了',
      })
    }

  },
  /**
   * 判断是否点赞
   */
  isLike() {
    db.collection('p_pet_like').where({
      petId: this.data.petId,
      openId: wx.getStorageSync("openid")
    }).get({
      success: res => {
        if (res.data.length > 0) {
          this.setData({
            picLiker: 1,
            pet_like_id: res.data[0]._id
          })
        }
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  /**
   * 点赞写真集
   */
  likePet: function () {
    let that = this;
    if (that.data.picLiker == 1) {
      // 取消收藏
      db.collection('p_pet_like').doc(that.data.pet_like_id).remove({
        success: function () {
          that.setData({
            picLiker: 0
          })
          that.updatePicLike(-1);
        },
        fail: function () { }
      })
    } else {
      // 收藏
      var like = {
        petId: this.data.petId,
        openId: wx.getStorageSync("openid"),
      }
      db.collection('p_pet_like').add({
        data: like
      }).then(() => {
        this.isLike();
        this.updatePicLike(1);
      })
    }
  },
  /**
   * 更新写真集点赞数量
   * @param {id} e 
   */
  updatePicLike(type) {
    let that = this;
    db.collection('p_pets').doc(that.data.petId).update({
      data: {
        picLikeCount: that.data.picLikeCount + type,
      }
    }).then(res => {
      that.setData({
        picLikeCount: that.data.picLikeCount + type
      })
    })
  },
  imgPreview: function (e) {
    let url = [];
    url.push(e.currentTarget.dataset.src);
    wx.previewImage({
      current: e.currentTarget.dataset.src,
      urls: url
    })
  },
  imgUpload: function () {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        let src = res.tempFilePaths[0];
        that.uploadPic(src);
      }
    })
  },
  /**
   * 上传图片到微信云存储
   */
  uploadPic(src) {
    this.loadProgress();
    let filePath = src;
    let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
    wx.cloud.uploadFile({
      cloudPath: "petPic/" + new Date().getTime() + suffix,
      filePath: filePath, // 文件路径
    }).then(res => {
      this.savePetPic(res.fileID);
      let arr = this.data.uploadImgs;
      arr.push(res.fileID);
      this.setData({
        uploadImgs: arr
      })
    }).catch(error => {
      console.log(error)
    })
  },
  savePetPic(src) {
    let date = new Date();
    let myDate = date.toLocaleDateString(); //获取当前日期
    var petPic = {
      activeFlag: 1, // 1 可用 0 不可用
      picPath: src, // 图片路径
      updateTime: myDate,
      petId: this.data.petId,
    }
    db.collection('p_pet_pics').add({
      data: petPic,
      loadProgress: 100
    }).then(res => {
      console.log("上传成功");
    })
  },
  checkboxChange: function (e) {
    let chooseList = this.data.chooseList;
    let index = e.currentTarget.dataset.aindex;
    chooseList[index] = !chooseList[index];
    this.setData({
      chooseList: chooseList
    })
  },
  openEdit: function () {
    let that = this;
    that.setData({
      showDeleteBtn: !that.data.showDeleteBtn
    });
  },
  deleteImg() {
    this.loadProgress();
    let chooseList = this.data.chooseList;
    let arrPicId = this.data.arrPicId;
    for (let i = 0; i < chooseList.length; i++) {
      if (chooseList[i]) {
        this.commitDeleteImg(arrPicId[i]);
      }
    }
    this.getPetPics();
  },
  /**
   * 执行删除操作  假删除
   */
  commitDeleteImg(id) {
    db.collection('p_pet_pics').doc(id).update({
      data: {
        activeFlag: 0,
        loadProgress: 100
      }
    }).then(res => {
      console.log(res)
    })
  },
  loadProgress() {
    this.setData({
      loadProgress: this.data.loadProgress + 3
    })
    if (this.data.loadProgress < 100) {
      setTimeout(() => {
        this.loadProgress();
      }, 100)
    } else {
      this.setData({
        loadProgress: 0
      })
    }
  }
})